﻿using System;
using System.Collections.Generic;
using System.Text;

namespace RuyeeModbus
{
    public class CRC
    {
        public static ushort CRC16(byte[] datas)
        {
            const ushort polinomio = 0xA001;
            ushort result = 0xFFFF;
            for (int i = 0; i < datas.Length; i++)
            {
                byte tmp = datas[i];
                result = (ushort)(tmp ^ result);
                for (int j = 0; j < 8; j++)
                {
                    if ((result & 0x0001) == 1)
                    {
                        result = (ushort)((result >> 1) ^ polinomio);
                    }
                    else
                    {
                        result = (ushort)(result >> 1);
                    }
                }
            }
            return result;
        }
        public static ushort CRC16(byte[] datas, int startIndex, int length)
        {
            const ushort polinomio = 0xA001;
            ushort result = 0xFFFF;
            if (startIndex > datas.Length - 1 || length > datas.Length)
            {
                Exception e = new Exception("计算参数超出CRC计算源数据界限");
                throw e;
            }
            for (int i = startIndex; i < length; i++)
            {
                byte tmp = datas[i];
                result = (ushort)(tmp ^ result);
                for (int j = 0; j < 8; j++)
                {
                    if ((result & 0x0001) == 1)
                    {
                        result = (ushort)((result >> 1) ^ polinomio);
                    }
                    else
                    {
                        result = (ushort)(result >> 1);
                    }
                }
            }
            return result;
        }
    }
}
